using System;
using System.Web.UI.HtmlControls;
using Navigant.Infrastructure.Helpers;

namespace Navigant.Web.UI
{
	public class ScrollableDiv : HtmlGenericControl
	{
		private HtmlInputHidden positionHidden;

		public ScrollableDiv() : base("div")
		{
		}

		public void ResetScroll()
		{
			this.positionHidden.Value = "0";
		}

		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);

			try
			{
				this.ID = "";

				this.positionHidden = new HtmlInputHidden();
				this.positionHidden.Value = "0";
				this.Controls.Add(this.positionHidden);

				string onScroll = "javascript: document.getElementById('" +
					this.positionHidden.UniqueID + "').value = this.scrollTop;";

				this.Attributes.Add("onscroll", onScroll);
				this.Style.Add("overflow", "auto");

				string script = "document.getElementById(\"" + this.ClientID + "\").scrollTop = " +
					"document.getElementById(\"" + this.positionHidden.UniqueID + "\").value;";

				script = "<script language=\"JavaScript\">if (typeof(addLoadEvent) == \"function\") " +
					"addLoadEvent(function() {" + script + "});</script>";

                string key = string.Format("{0}-StartUpScript", this.ClientID);
                if (!this.Page.ClientScript.IsStartupScriptRegistered(key))
                {
                    this.Page.ClientScript.RegisterStartupScript(this.GetType(),
                        key, script, false);
                }
			}
			catch (Exception ex)
			{
				Logger.LogError(ex);
			}
		}
	}
}